package xyz.xiangyushui.util.dataBase.seed;

import java.io.File;
import java.io.FileFilter;

import xyz.xiangyushui.dao.connectionFactory.JDBCConnectionFactory;
import xyz.xiangyushui.util.dataBase.DBUtil;
import xyz.xiangyushui.util.dataBase.SqlFileParser;

/**
 * Seeder is used to seed database with test data
 * @author Ivan
 *
 */
public class Seeder {
	private DBUtil db;
	private final String seedFilePath;
	
	public Seeder(){
		db=new DBUtil(new JDBCConnectionFactory());
		seedFilePath=System.getProperty("user.dir")+"/src/xyz/xiangyushui/util/dataBase/seed/";
	}
	
	/**
	 * seed all seeds file
	 */
	public void seed(){
		for(File f:getSeedFiles()){
			db.execute(SqlFileParser.loadSqlFile(f));
		}
	}
	
	/**
	 * seed specific seeds file
	 * @param fileName
	 */
	public void seed(String tableName){
		if(tableName==null){
			seed();
		}else{
			db.execute(SqlFileParser.loadSqlFile(new File(seedFilePath+"/"+tableName+"Seeder.sql")));
		}
	}
	
	/**
	 * delete all data in tables
	 */
	public void empty(){
		String [] tables=db.getAllTables("desserthouse");
		db.emptyTable(tables);
	}
	
	/**
	 * truncate specific table
	 * @param tableName
	 */
	public void empty(String tableName){
		if(tableName==null){
			empty();
		}else{
			db.emptyTable(tableName);
		}
	}
	
	private File[] getSpecificFiles(FileFilter f){
		return new File(seedFilePath).listFiles(f);
	}
	
	private File[] getSeedFiles(){
		return getSpecificFiles(f->f.getName().endsWith(".sql"));
	}
}
